package com.wl.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter
public class SessionFilter implements Filter {

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		System.out.println("-----------------sessionFilter过滤器处理/*-------------------");
		HttpServletRequest req = (HttpServletRequest) servletRequest;
		HttpServletResponse resp = (HttpServletResponse) servletResponse;
		HttpSession session = req.getSession();
		
		System.out.println("过滤器中的sessionId:"+session.getId());
		
		String contextPath = req.getContextPath();
		String uri = req.getRequestURI();
		
		System.out.println("当前用户id:"+session.getAttribute("userId"));

		if (session.getAttribute("userId") == null && !(uri.indexOf("login") > 0 
				|| uri.equalsIgnoreCase(contextPath) || uri.equalsIgnoreCase(contextPath+"/"))) {
			
			resp.sendRedirect(contextPath);
			
		} else {
			
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("----------------------sessionFilter过滤器初始化--------------------------");
	}

}
